package com.dede.getmusic.help

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Log
import com.lzy.okgo.OkGo
import okhttp3.Request
import org.jetbrains.anko.doAsync
import java.io.File
import java.io.FileOutputStream
import java.lang.ref.SoftReference
import java.text.SimpleDateFormat

/**
 * @author hsh
 * @date 2017/10/26 16:55.
 * @doc
 */
object ImageLoadHelper {

    private val nameFormat by lazy { SimpleDateFormat("YYYY-MM-dd") }
    private val TAG = "ImageLoadHelper"

    private val cacheMap by lazy { HashMap<String, SoftReference<Bitmap>>() }

    fun loadImage(context: Context, url: String): Bitmap? {
        val filename = nameFormat.format(System.currentTimeMillis())

        val bitmap = cacheMap[filename]
        if (bitmap != null && bitmap.get() !== null) {
            Log.i(TAG, "loadImage: 内存缓存")
            return bitmap.get()
        }

        val parentFile = File(context.applicationContext.cacheDir, "/img")

        if (!parentFile.exists())
            parentFile.mkdirs()

        val file = File(parentFile, filename)
        Log.i(TAG, "loadImage: 文件缓存路径" + file.absolutePath)

        return if (file.exists() && file.isFile && file.length() > 0) {
            Log.i(TAG, "loadImage: 文件缓存")
            val diskBitmap = BitmapFactory.decodeFile(file.absolutePath)
            cacheMap.put(filename, SoftReference(diskBitmap))
            diskBitmap
        } else {
            val request = Request.Builder().get().url(url).build()
            val response = OkGo.getInstance().okHttpClient.newCall(request).execute()
            if (response.isSuccessful) {
                val array = response.body()?.bytes() ?: kotlin.ByteArray(0)
                Log.i(TAG, "loadImage: 网络")
                val netBitmap = BitmapFactory.decodeByteArray(array, 0, array.size)
                doAsync {
                    cacheMap.put(filename, SoftReference(netBitmap))
                    val outputStream = FileOutputStream(file)
                    outputStream.write(array)
                    outputStream.close()
                }
                netBitmap
            } else {
                null
            }
        }
    }
}